import sys
import os
from shutil import copyfile, rmtree, move

cmd_arg_dict = {
    "--create": False,
    "--delete": False,
    "--archive-log": False,
    "--clean-cache": False
}

configurer_template_path = "common/templates/configurer_template.py"
configurer_test_template_path = "common/templates/configurer_test_template.py"
configurer_dir = "configurers/{}"
configurer_path = configurer_dir + "/{}.py"
configurer_test_path = configurer_dir + "/{}_test.py"


def create_configurer(configurer_name):
    configurer_target_path = configurer_path.format(
        configurer_name, configurer_name)
    configurer_test_target_path = configurer_test_path.format(
        configurer_name, configurer_name)

    if os.path.exists(configurer_dir.format(configurer_name)):
        print("Configurer already exists.")

    try:
        os.mkdir(configurer_dir.format(configurer_name))
    except:
        raise

    if os.path.exists(configurer_target_path):
        print("Configurer already exists.")
        return
    try:
        # render configurer template and move it to target position.
        with open(configurer_template_path, 'r') as f:
            content = f.read()
        with open(configurer_target_path, 'w+') as f:
            f.write(content.replace("{CONFIGURER_NAME}", configurer_name))

        # render configurer test template and move it to target position.
        with open(configurer_test_template_path, 'r') as f:
            content = f.read()
        with open(configurer_test_target_path, 'w+') as f:
            f.write(content.replace("{CONFIGURER_NAME}", configurer_name))

        # create logs folder for eache configurer.
        # all logs of that configurer could be found under that directory.
        os.mkdir("logs/" + configurer_name)

    except:
        raise


def delete_configurer(configurer_name):
    # delete logs, performing --archive-log before deletion is recommended.
    log_path = "./logs/"+configurer_name
    if os.path.exists(log_path):
        rmtree(log_path)
        print(configurer_name + "'s logs removed")
    else:
        print(configurer_name + "'s log folder not found, ignoring....")

    # delete configurer
    if os.path.exists(configurer_dir.format(configurer_name)):
        try:
            rmtree(configurer_dir.format(configurer_name))
            print(configurer_name + "'s folder removed")
        except:
            raise
    else:
        print(configurer_name + "'s configurer folder not found, ignoring....")
    print("Deletion completed.")


# move logs of a configurer into the archive folder.
# [default:(WORKING_DIR)/logs/archives]
def archive_log(configurer_name):
    try:
        move("./logs/"+configurer_name,
             "./logs/archives/"+configurer_name+".achived")
    except:
        raise

# delete temp file manually.


def clean_cache():
    try:
        rmtree("./tmp")
    except:
        raise


action_map = {
    "--create": create_configurer,
    "--delete": delete_configurer,
    "--archive-log": archive_log,
    "--clean-cache": clean_cache
}


def perform(action, configurer_name):
    action_map.get(action)(configurer_name)


if __name__ == "__main__":
    print(sys.argv[1:])

    for k, v in cmd_arg_dict.items():
        if k in sys.argv:
            cmd_arg_dict[k] = True

    if("--clean-cache" in sys.argv[1:]):
        cmd_arg_dict["--clean-cache"] = True

    print(cmd_arg_dict)

    if list(cmd_arg_dict.values()).count(True) != 1:
        print("Multiple actions found:\n" +
              str([k for k, v in cmd_arg_dict.items() if v is True]) +
              "\nPlease perform ONLY ONE action a time!: " + "")
        exit(0)

    action = [key for key, value in cmd_arg_dict.items() if value is True][0]
    action_index = sys.argv.index(action)

    if action_index == 0 or action_index >= len(sys.argv):
        print("Please specify the name of configurer to be manuplated.")
        exit(0)

    configurer_name = sys.argv[action_index + 1]

    print("performing action: " +
          action + " " + configurer_name +
          " ...")

    perform(action, configurer_name)
